<?php
namespace app\index\controller;

use app\common\controller\HomeBase;
use think\Db;
use think\facade\Env;
use wxkxklmyt\Scws;
use XSDocument;

class Api extends HomeBase
{
    /**
     * 分类列表
     */
    public function category_list()
    {
        $key = $this->request->param("key");
        $list = model("category")->where(['status' => 1])->field(['id','pid','name'])->select();
        return $this->echoJson(array2level($list));
    }

    function test()
    {
        $fielPath = Env::get('app_path') . "config/yuanwenku.ini";
        $xs =  new \XS($fielPath);
        $index = $xs->getIndex();
        $search = $xs->getSearch();

        $search->setQuery("数学");
        $docs = $search->search();

        print_r($search->getDbTotal());

        print_r($docs);


//        $data = array(
//            'uid' => 234, // 此字段为主键，必须指定
//            'title' => 'ppt  dasd asd ',
//            'content' => '测试文档的内容部分',
//            'time' => date('Y-m-d H:i:s',time())
//        );
//
//        // 创建文档对象
//        $doc = new XSDocument;
//        $doc->setFields($data);
//
//        // 添加到索引数据库中
//        $index->add($doc);

    }


    /**
     * 添加文档
     */
    public function add()
    {

        if ($this->request->isPost())
        {
            $data = $this->request->only(['key','title','cid','content','ext','preview','file_name','bid','size','total_page']);

            if($data['key'] != $this->siteConfig['site_key']) {
                $this->echoJson('秘钥不正确');
            }
            unset($data['key']);

            $data['sort'] = 0;
            $data['status'] = 1;
            $data['create_time'] = time();

            $validate_result = $this->validate($data, 'Article');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                if (empty($data['tags'])) {
                    $scws = new Scws();
                    $data['tags'] = $scws->scws($data['title'],5,true,",");
                }

                $res = model("article")->allowField(true)->insert($data);
                $uid = Db::name("article")->getLastInsID();

                if ($res) {

                    //迅搜入库
                    $fielPath = Env::get('app_path') . "config/yuanwenku.ini";
                    $xs =  new \XS($fielPath);
                    $index = $xs->getIndex();

                    $doc = new XSDocument;
                    $doc->setFields([
                        'uid' => $uid,
                        'title' => $data['title'],
                        'content' => $data['content'],
                        'date' => date('Y-m-d H:i:s',time())
                    ]);

//                    $index->beginRebuild();
                    $index->add($doc)->flushIndex();
//                    $index->endRebuild();

                    $this->echoJson('保存成功');
                } else {
                    $this->echoJson('保存失败');
                }
            }
        }

    }
}
